package 线程安全.多线程;

import com.sun.org.apache.xml.internal.security.Init;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class ChatRoomServer {
    private Selector selector = null;
    static final int port = 9999;
    private Charset charset = StandardCharsets.UTF_8;
    private static HashSet<String> users = new HashSet<>();
    private static String USER_EXIST = "system message: user exist, please change a name";
    //相当于自定义协议格式，与客户端协商好
    private static String USER_CONTENT_SPILIT = "#@#";

    private static boolean flag = false;

    public void init() throws IOException {
        selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress(port));
        server.configureBlocking(false);

        server.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("server is      listening now...");
        while (true) {
            int selectCount = selector.select();
            if (selectCount == 0)
                continue;
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectedKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                iterator.remove();
                dealWithSelectionkey(server, next);
            }
        }

    }

    private void dealWithSelectionkey(ServerSocketChannel server, SelectionKey next) throws IOException {
        if (next.isAcceptable()) {
            SocketChannel sc = server.accept();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_ACCEPT);
            next.interestOps(SelectionKey.OP_ACCEPT);
            System.out.println("Server is listening from client :" + sc.getRemoteAddress());
            sc.write(charset.encode("Please input your name."));
        }


    }
}
